package com.mashuai.utils.base;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mashuai.utils.toolkit.achieve.MsExegesis;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @ClassName: MsAopUtils
 * @Description: aop常用的一些工具
 */
@MsExegesis("spring的aop一些工具，避免动态代理无法获取实例")
public class MsAopUtils implements HandlerInterceptor {

    /**
     * 获取切点
     **/
    public static MethodSignature getMethodSignature(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature;
    }

    /**
     * 获取类名称
     **/
    public static String getClassName(JoinPoint joinPoint) {
        return joinPoint.getTarget().getClass().getName();
    }

    /**
     * 获取方法名称
     **/
    public static String getMethodName(JoinPoint joinPoint) {
        return joinPoint.getSignature().getName();
    }

    /**
     * 获取方法的参数
     **/
    public static Object[] getMethodParams(JoinPoint joinPoint) {
        return joinPoint.getArgs();
    }


    /**
     * 获取指定切点的执行的方法对象
     *
     * @param joinPoint
     * @return
     * @author mashuai
     */

    public static Method getMethod(JoinPoint joinPoint) {
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        Method method = methodSignature.getMethod();
        return method;
    }


    /**
     * 获取指定切点的执行的class类
     * 目前处理了mp的代理对象
     *
     * @param joinPoint
     * @return
     * @author mashuai
     */

    public static Class<?> getClass(JoinPoint joinPoint) throws Exception {
        Object target = joinPoint.getTarget();
        if (MsProxyUtils.isProxyClass(target)) {
            //如果是mapper层接口,获取实际代理的对象值
            if (target instanceof BaseMapper) {
                Class<?> mpProxyClass = MsProxyUtils.getMpProxyClass(target);
                return mpProxyClass;
            }
        }
        return target.getClass();
    }

    /**
     * 获取指定切点，方法上的注解信息
     *
     * @param joinPoint 获取拦截方法上的注解信息
     * @param mClass    注解
     * @return
     * @author mashuai
     */

    public static <M extends Annotation> M getAnnotation(JoinPoint joinPoint, Class<M> mClass) {
        return getMethod(joinPoint).getAnnotation(mClass);
    }

}
